package com.eboss2.sbs.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.ServiceGoodsOrderListManagerAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.interfaces.ServiceGoodsOrderCallbackListener;
import com.eboss2.sbs.model.ServiceGoodsOrderInfo;
import com.eboss2.sbs.myapplication.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.views.MyDialog;
import com.mytools.tool.views.MyListView;
import com.mytools.tool.views.SegmentView;
import com.tool.utils.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ServiceGoodsOrderListManagerActivity extends BaseActivity implements SegmentView.onSegmentViewClickListener, OnItemClickListener, View.OnClickListener {

	private PullToRefreshScrollView pullToRefreshScrollView;
	private SegmentView segView;//可以隐藏中间的按钮
	private MyListView listview;
	private ServiceGoodsOrderListManagerAdapter adapter;
	private List<ServiceGoodsOrderInfo> serviceGoodsOrderInfos = new ArrayList<>();
//	private EditText tv_search_key;
	private int state = 0;
	private int page = 1;
	private int rows = Config.ROWS;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_service_good_order_list);
		MyActivityManager.getInstance().addActivity(this);
		initView();
	}

	private void initView(){
		RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
		relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
		setTvText(R.id.tv_title, "预约订单管理 ");
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);






		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new MyOnRefreshListener());
		pullToRefreshScrollView.setMode(Mode.BOTH);

		listview = (MyListView)findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		adapter = new ServiceGoodsOrderListManagerAdapter(this, serviceGoodsOrderInfos, new ServiceGoodsOrderCallbackListener() {

			@Override
			public void commit(final long id, final long memberId, final int type, final String orderNo) {
//				startActivity(new Intent(mContext, MyEditShopStoreActivity.class).putExtra("id", id));
				MyDialog.Builder builder = new MyDialog.Builder(mContext);
				builder.setTitle("提示");
				builder.setMessage(type == 1 ? "确定预约订单?"  : "确定拒绝预约订单？");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (type == 1) {
							doCommint(id, type);
						}else {
							doRefundCommint(id, memberId, orderNo, 2);
						}
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
					}
				});
				builder.create().show();
			}

			@Override
			public void refund(final long id, final long memberId, final String orderNo) {

				MyDialog.Builder builder = new MyDialog.Builder(mContext);
				builder.setTitle("提示");
				builder.setMessage("确定取消预约订单？");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						doRefundCommint(id, memberId, orderNo, 4);
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
					}
				});
				builder.create().show();

			}

			@Override
			public void checkDetail(long id) {
//				startActivity(new Intent(mContext, ActivityProductDetails.class).putExtra("id", id));
			}
		});
		listview.setAdapter(adapter);

		segView = (SegmentView)findViewById(R.id.segView);
		segView.setOnSegmentViewClickListener(this);
		segView.setTextValues(new String[]{"待确认","确认", "拒绝", "取消"});



	}




	@Override
	protected void onResume() {
		super.onResume();
		refreshData();
	}

	class MyOnRefreshListener implements OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(Mode.BOTH);
			String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			page++;
			getdata();
		}
	}

	private void refreshData(){
//		refreshUi();
		serviceGoodsOrderInfos.clear();
		page = 1;
		getdata();
	}

	private void getdata(){

		String url = Config.SBS_ORDER_SERVICE_YY_LIST;
		RequestParams params = new RequestParams();
		params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid()+"");
		params.put("isVerify", state);
		params.put("pageNo",page+"");
		params.put("pageSize","15");
		showProgress("加载中...");

		HttpUtil.get(url, params, new HttpUtil.RequestListener() {

			@Override
			public void success(String response) {
				disShowProgress();
				try {

					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						// 刷新完成
						pullToRefreshScrollView.onRefreshComplete();
						return;
					}
					JSONObject obj = result.getJSONObject("data");
					String resultData = obj.optString("result");
					if (!StringUtils.isBlank(resultData)) {

						Gson gson = new Gson();
						// json数据转换成List
						List<ServiceGoodsOrderInfo> datas = gson.fromJson(resultData, new TypeToken<List<ServiceGoodsOrderInfo>>() {
						}.getType());


						if (datas.size() > 0) {
							serviceGoodsOrderInfos.addAll(datas);
							if (serviceGoodsOrderInfos.size() > 0) {
								linearLayout(R.id.id_no_data).setVisibility(View.GONE);
								listview.setVisibility(View.VISIBLE);
							} else {
								linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
								listview.setVisibility(View.GONE);
							}

						} else {
							if (serviceGoodsOrderInfos.size() > 0) {

								linearLayout(R.id.id_no_data).setVisibility(View.GONE);
								listview.setVisibility(View.VISIBLE);
								handler.postDelayed(new Runnable() {

									@Override
									public void run() {
										showErrorMsg("没有更多数据");
									}
								}, 1000);
							} else {
								linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
								listview.setVisibility(View.GONE);
							}
						}
					}
					// 刷新完成
					pullToRefreshScrollView.onRefreshComplete();
					adapter.notifyDataSetChanged();



				} catch (JSONException e) {
					e.printStackTrace();
					pullToRefreshScrollView.onRefreshComplete();
				}
			}

			@Override
			public void failed(Throwable error) {
				pullToRefreshScrollView.onRefreshComplete();
				showE404();
				disShowProgress();
			}
		});
	}



	private void doCommint(long id, int type) {
		String url = Config.SBS_ORDER_SERVICE_YY_VERIFY;
		RequestParams params = new RequestParams();
		params.put("isVerify", type);
		params.put("orderId", id);
		showProgress("加载中...");

		HttpUtil.get(url, params, new HttpUtil.RequestListener() {

			@Override
			public void success(String response) {
				disShowProgress();
				try {


					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						return;
					}
					refreshData();


				} catch (JSONException e) {
					e.printStackTrace();

				}
			}

			@Override
			public void failed(Throwable error) {

				showE404();
				disShowProgress();
			}
		});

	}


	private void doRefundCommint(final long id, long memberId, String orderNo, final int type) {
		String url = Config.SBS_ORDER_SERVICE_REFUND;
		RequestParams params = new RequestParams();
		params.put("memberId", memberId);
		params.put("orderId", orderNo);
		showProgress("加载中...");

		HttpUtil.post(url, params, new HttpUtil.RequestListener() {

			@Override
			public void success(String response) {
				disShowProgress();
				try {


					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						return;
					}
//					refreshData();

					doCommint(id, type);


				} catch (JSONException e) {
					e.printStackTrace();

				}
			}

			@Override
			public void failed(Throwable error) {

				showE404();
				disShowProgress();
			}
		});

	}






	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			default:break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//		Intent intent = new Intent();
//		intent.setClass(mContext, ActivityProductDetails.class);
////		intent.putExtra("id", datas.get(position).getId());
//		startActivity(intent);

		startActivity(new Intent(mContext, ActivityServiceGoodsOrderDetail.class).putExtra("data", serviceGoodsOrderInfos.get(position)));

	}

	@Override
	public void onSegmentViewClick(int index) {

		if (index == 3) {
			state = index+1;
		}else{
			state = index;
		}

		refreshData();
	}






	
}
